<?php


namespace app\admin\controller;

use think\Controller;
use app\common\services\ConfirmReceipt;

class Timing extends Controller
{
    // 确认收货后，变更金额
    public function index()
    {
        $send = date("Y-m-d H:i:s", strtotime("-7 day"));
        $send = model('order')
            ->where('or_status', 2)
            ->whereTime('deliver_time', '<=', $send)
            ->column('id');

        // 订单更新
        //$update = db('order')->whereIn('id', $send)->update(['or_status' => 3]);
        db('order')->whereIn('id', $send)->update(['or_status' => 3]);


        $send = 584;
        if (!empty($send)){
            // 金额重新调整
            $tz = new ConfirmReceipt();
            // 符合时间订单id
            $tz->index($send);
        }

//        if ($update) {
//            return '更新成功';
//        } else {
//            return '更新失败';
//        }
    }

    // 一百家店主自动升级运营中心
    public function remove()
    {
        $time = date('Y-m-d H:i:s');
       $us_type =  model('user')->where('us_type',2)->column('id');
       foreach ($us_type as $k=>$v){
           // 查询直推店主个数
         $dianNum = model('user')->where('us_pid',$v)->where('us_type',2)->count();
         if ($dianNum >=100)
         {
             // 获取该用户的所有下级，用于计算分离前业绩
             $usInfo = model('User')->where('id',$v)->find();
             $teams =  $this->getAllChildrenId($v);
             array_unshift ($teams,$v);

             $teamMoney = model('MoneyDetailed')
                 ->whereIn('us_id',$teams)->sum('money');

             model('User')->where('id',$v)
                 ->update(['yun_yuan_pid'=>$usInfo['us_pid'],'yun_yuan_yeji'=>$teamMoney,'us_pid'=>0,'cheng_yun_time'=>$time]);

              // 确认修改会员身份
             model('User')->editInfo(['us_type' => 3], ['id' => $v]);
         }
       }
    }

    public function getAllChildrenId($id)
    {
        $ids = $this->getChildrenId($id) ?? [];
        $noHandleIds = $ids;
        while (!empty($noHandleIds)) {
            $id = array_shift($noHandleIds);
            $childrenIds = $this->getChildrenId($id);
            foreach ($childrenIds as $v) {
                array_push($ids, $v);
                array_push($noHandleIds, $v);
            }
        }
        return $ids;
    }

    public function getChildrenId($id)
    {
        return db('user')
            ->where('us_pid', $id)
            ->column("id");
    }

}